package com.shigu.component.shiro.filter;

import com.shigu.user.service.MallTokenService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;

/**
 *  郭尔
 * created on 2019/1/27
 */
@Service("appLoginFilter")
public class AppLoginFilter implements Filter {
    @Autowired
    MallTokenService mallTokenService;

    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
    }

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        HttpServletRequest request= (HttpServletRequest) servletRequest;
        HttpServletResponse response= (HttpServletResponse) servletResponse;
        String token=request.getParameter("token");
        if (StringUtils.isEmpty(token)) {//没上传token是错误的
           writeToResponse(response,"{\"success\":false,\"msg\":\"用户请登陆\",\"api\":false}");
            return;
        }
        //验证对错
        Long userId=mallTokenService.selUserIdByToken(token);
        if (userId == null) {
            writeToResponse(response,"{\"success\":false,\"msg\":\"登录信息失效\",\"api\":false}");
            return;
        }
        filterChain.doFilter(servletRequest,servletResponse);
    }

    public static void writeToResponse(HttpServletResponse response, String jsonString){
        response.setCharacterEncoding("UTF-8");
        response.setContentType("application/json");//修复post异常信息未被解析为json
        PrintWriter writer;
        try {
            writer = response.getWriter();
            writer.print(jsonString);
            writer.flush();
            writer.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    @Override
    public void destroy() {

    }

}
